﻿Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日   
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var count = 0;
var dialog = null;


//jQuery  validate 插件 的bug 补丁  ,解决了 多个name 只验证第一个 name的问题
if ($.validator) {
    //fix: when several input elements shares the same name, but has different id-ies....
    $.validator.prototype.elements = function () {

        var validator = this,
            rulesCache = {};

        // select all valid inputs inside the form (no submit or reset buttons)
        // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
        return $([]).add(this.currentForm.elements)
        .filter(":input")
        .not(":submit, :reset, :image, [disabled]")
        .not(this.settings.ignore)
        .filter(function () {
            var elementIdentification = this.id || this.name;

            !elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this);

            // select only the first element for each name, and only those with rules specified
            if (elementIdentification in rulesCache || !validator.objectLength($(this).rules()))
                return false;

            rulesCache[elementIdentification] = true;
            return true;
        });
    };
}

if ($.validator) {
    $.validator.prototype.elements = function () {
        var validator = this,
			rulesCache = {};

        // select all valid inputs inside the form (no submit or reset buttons)
        return $(this.currentForm)
		.find("input, select, textarea")
		.not(":submit, :reset, :image, [disabled]")
		.not(this.settings.ignore)
		.filter(function () {
		    if (!this.name && validator.settings.debug && window.console) {
		        console.error("%o has no name assigned", this);
		    }

		    // select this element if this has the same name as one in cache (may be was dynamically added)
		    if (this.name in rulesCache) {
		        if (!validator.objectLength($(this).rules())) {
		            $(this).rules('add', rulesCache[this.name]);
		        }
		        return true;
		    }

		    // select only the element with rules specified
		    if (!validator.objectLength($(this).rules())) {
		        return false;
		    }

		    // Add rules to the cache
		    rulesCache[this.name] = $(this).rules();
		    return true;
		});
    };
}
//jQuery validate 插件补丁结束

function changeMoneyToChinese(money) {
    var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
    var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
    var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
    var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
    var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字

    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义

    if (money == "") {
        return "";
    }

    money = parseFloat(money);
    //alert(money);
    if (money >= maxNum) {
        $.alert('超出最大处理数字');
        return "";
    }
    if (money == 0) {
        ChineseStr = cnNums[0] + cnIntLast + cnInteger;
        //document.getElementById("show").value=ChineseStr;
        return ChineseStr;
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) {//获取整型部分转换
        zeroCount = 0;
        IntLen = IntegerNum.length;
        for (i = 0; i < IntLen; i++) {
            n = IntegerNum.substr(i, 1);
            p = IntLen - i - 1;
            q = p / 4;
            m = p % 4;
            if (n == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; //归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        //整型部分处理完毕
    }
    if (DecimalNum != '') {//小数部分
        decLen = DecimalNum.length;
        for (i = 0; i < decLen; i++) {
            n = DecimalNum.substr(i, 1);
            if (n != '0') {
                ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (ChineseStr == '') {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    }
    else if (DecimalNum == '') {
        ChineseStr += cnInteger;
    }
    return ChineseStr;

}
//js 数字转为中文的 金额函数


(function ($, window, document) {
    var defaults = {
        id: 0,
        url: '/',
        type: '',
        json:{},
        // deptUrl: '/ashx/dept/deptInfo.ashx',
        type: '',
        isRetail: 0
    };

    $.fn.invoiceDetail = function (options) {
        var config = $.extend({}, defaults, options);
        var self = $(this);


            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            // var pdialog = frameElement.dialog;
            // var tdata = pdialog.get("data");
            // if (tdata.rows) {
            //     var pdata = tdata.rows[0];
            //     if (pdata.zfbz) {
            //         if (pdata.chfpid != null || pdata.chyfpid) {
            //             $("#invbg").prepend("<div id='redseal'></div>");
            //         } else {
            //             $("#invbg").prepend("<div id='voidseal'></div>");
            //         }
            //     } else if (pdata.retention > 0) {
            //         $("#invbg").prepend("<div id='rententionseal'></div>");
            //     }
            // }

            //含税不含税按钮
            //TODO: 客户不需要 含税的按钮  默认设置为不含税
            window.hasTax = true;
            if (window.hasTax) {
                $("#tdj").text("单价(含税)");
                $("#tje").text("金额(含税)");
                $("#hastax").text("含税");
            } else {
                $("#tdj").text("单价(不含税)");
                $("#tje").text("金额(不含税)");
                $("#hastax").text("不含税");
            }

            //$("#hastax").click(function () {
            //    var je = $("#dt").find("input[name='je']");
            //    var se = $("#dt").find("input[name='se']");
            //    var dj = $("#dt").find("input[name='dj']");
            //    var slv = $("#dt").find("select[name='slv'] ,input[name='slv']");
            //    var sl = $("#dt").find("input[name='sl']");

            //    var self = $(this);
            //    var text = self.text();
            //    if (text == "含税") {
            //        window.hasTax = false;
            //        self.text("不含税");
            //        $("#tdj").text("单价(不含税)");
            //        $("#tje").text("金额(不含税)");

            //        je.each(function (i, item) {
            //            var mslv = $(slv[i]);
            //            var mje = $(je[i]);
            //            var mdj = $(dj[i]);
            //            var mse = $(se[i]);
            //            var msl = $(sl[i]);

            //            var fslv = parseFloat(mslv.val());
            //            var fje = parseFloat(mje.val());

            //            if(!isNaN(fslv) && !isNaN(fje)) {
            //                var rse = fje * fslv;
            //                mse.val(rse);
            //            }

            //        });
            //        setSum();
            //    } else if (text == "不含税") {
            //        window.hasTax = true;
            //        self.text("含税");
            //        $("#tdj").text("单价(含税)");
            //        $("#tje").text("金额(含税)");
            //        je.each(function (i, item) {
            //            var mslv = $(slv[i]);
            //            var mje = $(je[i]);
            //            var mdj = $(dj[i]);
            //            var mse = $(se[i]);
            //            var msl = $(sl[i]);

            //            var fslv = parseFloat(mslv.val());
            //            var fje = parseFloat(mje.val());

            //            if (!isNaN(fslv) && !isNaN(fje)) {
            //                var rse = (fje / (parseFloat(1) + fslv) )* fslv;
            //                mse.val(rse);
            //            }
            //        });
            //        setSum();
            //    }
            //});


            var html = "";
            //表单验证, 查询界面不用验证
            if (config.type == "query" || config.type == "red") {

            } else {

                $.validator.addMethod("decimal2", function (value, element) {
                    return this.optional(element) || /^(-|\d)+(\.\d{1,2})?$/.test(value);
                }, "小数位不能超过两位");
                $.validator.addMethod("decimal4", function (value, element) {
                    return this.optional(element) || /^(-|\d)+(\.\d{1,4})?$/.test(value);
                }, "小数位不能超过四位");
                $.metadata.setType("attr", "validate");
                var trule = {
                    khmc: {
                        required: true
                    },
                    khsh: {
                        required: true
                    },
                    spmc: {
                        required: true
                    },
                    // ggxh: {
                    //     required: true
                    // },
                    // jldw: {
                    //     required: true
                    // },
                    // sl: {},
                    // dj: {
                    //     required: true
                    // },
                    je: {
                        required: true,
                        decimal2: true
                    },
                    se: {
                        required: true
                    },
                    sumje: {
                        maxlength: 11
                    }
                };
                var tmessage = {
                    khmc: {
                        required: "商户名必须填写"
                    },
                    khsh: {
                        required: "税号必须填写"
                    },
                    spmc: {
                        required: "商品名称必须填写"
                    },
                    // ggxh: {
                    //     required: "规格型号必须填写"
                    // },
                    // jldw: {
                    //     required: "计量单位必须填写"
                    // },
                    // sl: {},
                    // dj: {
                    //     required: "单价必须填写"
                    // },
                    je: {
                        required: "必须填写金额",
                        decimal2: "只能有两位小数"
                    },
                    se: {
                        required: "税额必须填写"
                    },
                    maxlength: {
                        maxlength: "金额超长"
                    }
                }
                // if (config.isRetail == 1) {
                //     trule.sl.required = true;
                //     trule.sl.decimal4 = true;
                //
                //     tmessage.sl.required = "数量必须填写";
                //     tmessage.sl.decimal4 = "最多只能四位小数";
                // } else {
                //     trule.sl.required = true;
                //     trule.sl.decimal2 = true;
                //
                //     tmessage.sl.required = "数量必须填写";
                //     tmessage.sl.decimal2 = "最多只能两位小数";
                // }
                //Todo: 表单验证
                $("form").validate({
                    submitHandler: function (form) {
                        return false;
                    },
                    errorPlacement: function (error, element) {
                        var nextCell = element.parents("td");
                        if (!nextCell.length) {
                            nextCell = element.parents("#khhContainer");
                        }
                        // nextCell.find("div.l-exclamation").remove();
                        // $('<div class="l-exclamation" title="' + error.html() + '"></div>').appendTo(nextCell).ligerTip();
                    },
                    success: function (element) {
                        $(".l-exclamation").remove();
                        $(".l-verify-tip-corner").remove();
                        $(".l-verify-tip-content").remove();
                    },
                    rules: trule,
                    messages: tmessage
                });
            }


            $("#invoiceId").attr("readonly", "readonly");
            $("#invoiceNo").attr("readonly", "readonly");
            // $("#kpsj").attr("readonly", "readonly");
            // $("#khmc").attr("readonly", "readonly");
            // $("#khsh").attr("readonly", "readonly");
            // $("#dzdh").attr("readonly", "readonly");
            // $("#dh").attr("readonly", "readonly");
            // $("#yhzh").attr("readonly", "readonly");
            // $("#khyh").attr("readonly", "readonly");
            // $("#khh").attr("readonly", "readonly");

            $("#sumje").attr("readonly", "readonly");
            $("#sumse").attr("readonly", "readonly");
            $("#sumhans").attr("readonly", "readonly");
            $("#sum").attr("readonly", "readonly");

            var deptParams = {}
            // if (dialog.get("data").rows) {
            //     var deptData = dialog.get("data").rows[0];
            //     if (deptData.sqrid) {
            //         deptParams.uid = deptData.sqrid;
            //     }
            // }

            //Todo:获取销方信息
            // $.post(config.deptUrl, deptParams, function (res) {
            //     var data = res[0];
            //     $("#xfmc").attr("readonly", "readonly").val(data.dwmc);
            //     $("#xfsh").attr("readonly", "readonly").val(data.dwsh);
            //     $("#xfdzdh").attr("readonly", "readonly").val(data.bgdz + "   " + data.lxdh);
            //     $("#xfyhzh").attr("readonly", "readonly").val(data.khyh + "   " + data.yhzh);
            //
            // }, "json");


            //Todo:选择客户
            window.companyInfo = {};
            $("#triangle").click(function (e) {
                window.cIndex = layer.open({
                    type: 2,
                    id: 'mycompany',
                    title: '查询公司',
                    fixed: true,
                    scrollbar: false,
                    area: ['750px', '580px']
                    , content: '/manual/company'
                    ,end:function(){
                        if ($.isEmptyObject(companyInfo)) {
                            return ;
                        }
                        $("#companyid").val(companyInfo.id);
                        $("#khmc").val(companyInfo.khmc);
                        $("#khsh").val(companyInfo.khsh);
                        $("#dzdh").val(companyInfo.address);
                        $("#dh").val(companyInfo.phone);
                        $("#khyh").val(companyInfo.bank);
                        $("#yhzh").val(companyInfo.bankaccount);

                        companyInfo = {};
                    }
                });
            });

            //获取总的信息
            function getRow(count) {
                var row = '<tr id="d_row' + count + '" class="bg_uncheck">' +
                    '<td width="17px"><input type="checkbox" attr="add" style="margin:1px" value="d_row' + count + '" /></td>' +
                    '<td width="184px"><input type="text"attr="add" name="spmc" readonly="readonly" style="width:165px;" /><input type="hidden" attr="add"  name="spbm" /><input type="hidden" attr="add"  name="productid" /><img class="triangle" src="/js/plugin/css/invoice/img/triangle-down.png" /></td>' +
                    '<td width="79px"><input type="text"attr="add" name="ggxh" style="width:60px;" /></td>' +
                    '<td width="64px"><input type="text"attr="add" name="jldw" style="width:40px;" /></td>' +
                    '<td width="69px"><input type="text"attr="add" name="sl" style="width:40px;" /></td>' +
                    '<td width="94px"><input type="text"attr="add" name="dj" style="width:70px;" /></td>' +
                    '<td width="109px"><input type="text"attr="add" name="je" style="width:75px;" /></td>' +
                    '<td width="64px">' +
                    '<select name="slv" attr="add" style="width:50px;background-color:transparent;" >' +
                    '<option value="0">0%</option>' +
                    '<option value="0.06">6%</option>' +
                    '<option value="0.10">10%</option>' +
                    '<option value="0.13" selected="selected">13%</option>' +
                    '</select>' +
                    '</td>' +
                    '<td width="101px"><input type="text" attr="add" name="se" style="width:75px;" /></td>' +
                    '</tr>';
                return row;
            }

            //获取税率
            function getTaxRate(slv) {
                var selectBox = "";
                slv = parseFloat(slv);
                switch (slv) {
                    case 0:
                        selectBox = '<option value="0" selected="selected">0%</option>' +
                            '<option value="0.06">6%</option>' +
                            '<option value="0.10">10%</option>' +
                            '<option value="0.13">13%</option>';
                        break;
                    case 0.06:
                        selectBox = '<option value="0">0%</option>' +
                            '<option value="0.06" selected="selected">6%</option>' +
                            '<option value="0.10">10%</option>' +
                            '<option value="0.13">13%</option>';
                        break;
                    case 0.10:
                        selectBox = '<option value="0">0%</option>' +
                            '<option value="0.06">6%</option>' +
                            '<option value="0.10" selected="selected">10%</option>' +
                            '<option value="0.13">13%</option>';
                        break;
                    case 0.13:
                        selectBox = '<option value="0">0%</option>' +
                            '<option value="0.06">6%</option>' +
                            '<option value="0.10">10%</option>' +
                            '<option value="0.13" selected="selected">13%</option>';
                        break;
                    default:

                }
                return selectBox;
            }

            //获取明细信息 (查看界面)
            function getDetail(count, detail) {
                $("#triangle").hide();
                var selectBox = getTaxRate(detail.slv);
                var row = '<tr id="d_row' + count + '" class="bg_uncheck">' +
                    '<td width="17px"></td>' +
                    '<td width="184px"><input type="text" name="spmc" style="width:165px;" value="' + detail.spmc + '" /></td>' +
                    '<td width="79px"><input type="text" name="ggxh" style="width:60px;" value="' + detail.ggxh + '" /></td>' +
                    '<td width="64px"><input type="text" name="jldw" style="width:50px;"  value="' + detail.jldw + '" /></td>' +
                    '<td width="69px"><input type="text" name="sl" style="width:50px;" value="' + detail.sl + '" /></td>' +
                    '<td width="94px"><input type="text" name="dj" style="width:80px;" value="' + detail.dj + '" /></td>' +
                    '<td width="109px"><input type="text" name="je" style="width:80px;" value="' + detail.je + '" /></td>' +
                    '<td width="64px">' +
                    '<select name="slv" disabled="disabled" style="width:55px;;background-color:transparent;border:none" >' +
                    selectBox +
                    '</select>' +
                    '</td>' +
                    '<td width="101px"><input type="text" name="se" style="width:80px;" value="' + detail.se + '" /></td>' +
                    '</tr>';
                return row;
            }

            //获取明细信息  (修改界面)
            function getUpdateDetail(count, detail) {
                var selectBox = getTaxRate(detail.slv);
                var row = '<tr id="d_row' + count + '" class="bg_uncheck">' +
                    '<td width="17px"><input type="checkbox" attr="update" style="margin:1px" value="d_row' + count + '" /><input  type="hidden" attr="d_row' + count + '" name="id" value="' + detail.id + '" /></td>' +
                    '<td width="184px"><input type="text" name="spmc" style="width:165px;" attr="d_row' + count + '" style="" value="' + detail.spmc + '" /></td>' +
                    '<td width="79px"><input type="text" name="ggxh" attr="d_row' + count + '" style="width:60px;" value="' + detail.ggxh + '" /></td>' +
                    '<td width="64px"><input type="text" name="jldw" attr="d_row' + count + '" style="width:50px;"  value="' + detail.jldw + '" /></td>' +
                    '<td width="69px"><input type="text" name="sl" attr="d_row' + count + '" style="width:50px;" value="' + detail.sl + '" /></td>' +
                    '<td width="94px"><input type="text" name="dj" attr="d_row' + count + '" style="width:80px;" value="' + detail.dj + '" /></td>' +
                    '<td width="109px"><input type="text" name="je" attr="d_row' + count + '" style="width:80px;" value="' + detail.je + '" /></td>' +
                    '<td width="64px">' +
                    '<select attr="d_row' + count + '" name="slv" style="width:55px;background-color:transparent;border:none" >' +
                    selectBox +
                    '</select>' +
                    '</td>' +
                    '<td width="101px"><input type="text" name="se" attr="d_row' + count + '" style="width:80px;" value="' + detail.se + '" /></td>' +
                    '</tr>';
                return row;
            }

            //添加折扣明细行
            function getDiscountRowV(count, detail, type) {
                var row = '<tr id="d_row' + count + '" class="bg_check" attr="discount">';
                if (type == "update") {
                    row += '<td width="17px"><input type="checkbox" attr="update" style="margin:1px" value="d_row' + count + '" /><input  type="hidden" attr="d_row' + count + '" name="id" value="' + detail.id + '" /></td>';
                } else {
                    row += '<td width="17px"></td>';
                }
                row += '<td width="184px"><input type="text" style="width:165px;" attr="d_row' + count + '" name="spmc" readonly="readonly" value="' + detail.spmc + '" style="" /><input type="hidden" name="spbm" value="'+detail.spbm+'" /></td>' +
                    '<td width="79px"><input type="text"attr="d_row' + count + '" name="ggxh1" style="width:60px;" /></td>' +
                    '<td width="64px"><input type="text" attr="d_row' + count + '" name="jldw1" style="width:50px;" /></td>' +
                    '<td width="69px"><input type="text" attr="d_row' + count + '" name="sl1" style="width:50px;" /></td>' +
                    '<td width="94px"><input type="text" attr="d_row' + count + '" name="dj1" style="width:80px;" /></td>' +
                    '<td width="109px"><input type="text" attr="d_row' + count + '" name="je1" style="width:80px;" value="' + detail.je + '"/></td>' +
                    '<td width="64px"><input type="text" attr="d_row' + count + '" name="slv1" style="width:50px;" value="' + detail.slv * 100 + '%' + '"/></td>' +
                    '<td width="101px"><input type="text" attr="d_row' + count + '" name="se1" style="width:80px;" value="' + detail.se + '"/></td>' +
                    '</tr>';
                return row;
            }

            //添加折扣明细行
            function getDiscountRow(data, count) {
                var row = '<tr id="d_row' + count + '" class="bg_check" attr="discount">' +
                    '<td width="17px"><input type="checkbox" attr="add" style="margin:1px" readonly="readonly" value="d_row' + count + '" /></td>' +
                    '<td width="184px"><input type="text"attr="add" name="spmc" readonly="readonly" value="' + data.spmc + '" style="" /><input attr="add" name="spbm" value="'+data.spbm+'" type="hidden" /><input attr="add" type="hidden" value="'+data.productid+'" name="productid" /></td>' +
                    '<td width="79px"><input type="text"attr="add" name="ggxh" readonly="readonly" style="width:60px;" /></td>' +
                    '<td width="64px"><input type="text"attr="add" name="jldw" style="width:50px;" readonly="readonly" /></td>' +
                    '<td width="69px"><input type="text"attr="add" name="sl" style="width:50px;" readonly="readonly" /></td>' +
                    '<td width="94px"><input type="text"attr="add" name="dj" style="width:80px;" readonly="readonly" /></td>' +
                    '<td width="109px"><input type="text"attr="add" name="je" style="width:80px;" readonly="readonly" value="' + (data.zk * -1) + '" /></td>' +
                    '<td width="64px"><input type="text"attr="add" name="slv" style="width:50px;" readonly="readonly" value="' + data.slv + '"/></td>' +
                    '<td width="101px"><input type="text" attr="add" name="se" style="width:80px;" readonly="readonly" value="' + (data.se * -1) + '" /></td>' +
                    '</tr>';
                return row;
            }

            html += '<table id="dt">';
            if (config.id == 0) {//添加新的一行
                // if (config.type == "iccard") {
                //     var template = $.validator.format(getICCardRow(count));
                //     html += template(count);
                // } else {
                var template = $.validator.format(getRow(count));
                html += template(count)
                // }

                html += '</table>';
                self.append(html);
                //Todo:自动提示
                //     .find("input[name='spmc']").autocomplete({
                //     source: "../../../ashx/invoice/autocomplete.ashx",
                //     minLength: 2
                // });
                $("#dt tr").addClass("bg_uncheck");
            } else {
                if (config.type == 'query' || config.type == 'red') {
                    // $.post(config.url, {fid: config.id, hasTax: window.hasTax}, function (res) {
                    //     for (var i = 0; i < res.Data.length; i++) {
                    //         if (res.Data[i].spmc.indexOf("折扣") != -1) {
                    //             html += getDiscountRowV(count, res.Data[i], "query");
                    //         } else {
                    //             html += getDetail(count, res.Data[i]);
                    //         }
                    //         count++;
                    //     }
                    //     html += '</table>';
                    //     self.append(html);
                    //     $("#sumje").val(res.Sum);
                    //     $("#sumse").val(res.Tax);
                    //     $("#sumhans").val(res.BigTaxSum);
                    //     $("#sum").val(res.TaxSum);
                    //     $("input").attr("readonly", "readonly");
                    // }, 'json');
                    var res = $.parseJSON(config.json);
                    $("#khmc").val(res.khmc);
                    $("#khsh").val(res.khsh);
                    $("#dzdh").val(res.dzdh);
                    $("#dh").val(res.dh);
                    $("#khyh").val(res.khyh);
                    $("#yhzh").val(res.yhzh);
                    $("#bz").val(res.bz);
                    for (var i = 0; i < res.spmc.length; i++) {
                        var data = {};
                        data.spmc = res.spmc[i];
                        data.ggxh = res.ggxh[i];
                        data.jldw = res.jldw[i];
                        data.sl = res.sl[i];
                        data.dj = res.dj[i];
                        data.je = res.je[i];
                        data.slv = res.slv[i];
                        data.se = res.se[i];

                        html += getDetail(count, data);
                        count++;
                    }
                    html += '</table>';
                    self.append(html);
                    $("#sumje").val(res.Sum);
                    $("#sumse").val(res.Tax);
                    $("#sumhans").val(res.BigTaxSum);
                    $("#sum").val(res.TaxSum);
                    $("input").attr("readonly", "readonly");
                }

                if (config.type == 'update' || config.type == 'copy') {
                    $.post(config.url, {fid: config.id}, function (res) {
                        for (var i = 0; i < res.Data.length; i++) {
                            if (res.Data[i].spmc.indexOf("折扣") != -1) {
                                var template = $.validator.format(getDiscountRowV(count, res.Data[i], "update"));
                            } else {
                                var template = $.validator.format(getUpdateDetail(count, res.Data[i]));
                            }

                            html += template(count)
                            count++;
                        }
                        html += '</table>';
                        self.append(html);
                        //Todo:自动提示
                        //     .find("input[name='spmc']").autocomplete({
                        //     source: "../../../ashx/invoice/autocomplete.ashx",
                        //     minLength: 2
                        // });
                        $("#sumje").val(res.Sum);
                        $("#sumse").val(res.Tax);
                        $("#sumhans").val(res.BigTaxSum);
                        $("#sum").val(res.TaxSum);
                        if (config.type == 'update') {
                            $("table input").attr("readonly", "readonly");
                        }
                        calculator();
                    }, 'json');
                }

                $("#dt tr").css("backgroundColor", "#DCE6F0")
            }


            $("input:checkbox").click(function () {
                var stat = $(this).attr("checked");
                if (stat == true) {
                    $(this).parent().parent().removeClass("bg_uncheck").addClass("bg_check");
                } else {
                    $(this).parent().parent().removeClass("bg_check").addClass("bg_uncheck");
                }
            });

            ///添加明细按钮
            $("#addDetail").click(function (e) {
                var tr = $("#dt tr");
                if ((tr.length + 1) > 100) {
                    // if ($.ligerDialog) {
                    //     $.ligerDialog.warn("已经超出了100行明细");
                    // } else {
                    alert("已经超出了100行明细");
                    // }
                }
                else {
                    count++;
                    var template = $.validator.format(getRow(count));

                    $("#dt tbody").append(template(count)).addClass("bg_uncheck");
                    //Todo:自动提示
                    //     .find("input[name='spmc']")
                    //     .autocomplete({
                    //     source: "../../../ashx/invoice/autocomplete.ashx",
                    //     minLength: 3
                    // });
                }

            });

            ///添加折扣明细行
            $("#discount").click(function (e) {
                var tr = $("#dt tr");
                if ((tr.length + 1) > 100) {
                    if ($.ligerDialog) {
                        $.ligerDialog.warn("已经超出了100行明细");
                    } else {
                        alert("已经超出了100行明细");
                    }
                } else {
                    //var disc = $("tr[attr='discount']");
                    //if (disc.length == 0) {
                    //    count++;
                    //    var template = $.validator.format(getDiscountRow(count));
                    //    $("#dt").append(template(count));
                    //} else {
                    //    if ($.ligerDialog) {
                    //        $.ligerDialog.warn("只能添加一条折扣行");
                    //    } else {
                    //        alert("只能添加一条折扣行");
                    //    }
                    //}

                    var lastRow = tr[tr.length - 1];
                    var spmc = $(lastRow).find("input[name='spmc']").val();
                    var je = $(lastRow).find("input[name='je']").val();
                    var spbm = $(lastRow).find("input[name='spbm']").val();
                    var productid = $(lastRow).find("input[name='productid']").val();
                    var slv = $(lastRow).find("select").val();
                    if (spmc == "" && je == "") {
                        layer.msg("你没有添加行");
                        return;
                    }

                    window.dIndex = layer.open({
                        type: 2,
                        id: 'mydiscount',
                        title: '添加折扣',
                        fixed: true,
                        scrollbar: false,
                        area: ['450px', '180px']
                        , content: '/manual/discount'
                        ,btn: ['确认', '取消']
                        ,yes:function(index, layero){
                            var fIndex = layer.getFrameIndex("mydiscount");
                            var mform = layer.getChildFrame("form" , fIndex);
                            var sb = layer.getChildFrame("#sb" , fIndex);
                            var data = {};
                            $.each(mform.serializeArray() , function (index , val){
                                data[val.name] = val.value;
                            });
                            var zkje = data.discount;
                            var se = (zkje *parseFloat(slv) / (1+ parseFloat(slv))).toFixed(2);
                            console.log(se);
                            //为了触发验证
                            sb.trigger('click');
                            var discount = {
                                spmc : spmc,
                                spbm : spbm,
                                productid : productid,
                                zk : zkje,
                                slv : slv,
                                se : se
                            }
                            $("#dt").append(getDiscountRow(discount, ++count));
                        }
                    });

                    // if (spmc.indexOf("折扣") > 0) {
                    //     $.ligerDialog.error("不能连续添加折扣行");
                    //     return;
                    // }
                    // var win = $.ligerDialog.open({
                    //     title: '填写折扣', name: 'windiscount', width: 400, height: 280, url: '../../invoice/discount.aspx',
                    //     data: {
                    //         info: lastRow
                    //     },
                    //     buttons: [
                    //         {
                    //             text: '确定', onclick: function (item, dialog) {
                    //                 //var rowsdata = dialog.frame.liger.get("maingrid").getCheckedRows();
                    //                 var zk = dialog.frame.liger.get("form1").getData();
                    //                 var tslv = parseFloat(zk.slv);
                    //                 zk.se = ((parseFloat(zk.zk) / (1 + tslv)) * tslv).toFixed(3);
                    //                 $("#dt").append(getDiscountRow(zk, ++count));
                    //                 win.close();
                    //                 setSum();
                    //                 setTax();
                    //             }, cls: 'l-dialog-btn-highlight'
                    //         },
                    //         {
                    //             text: '取消', onclick: function () {
                    //                 win.close();
                    //             }
                    //         }
                    //     ]
                    // });


                }
            });

            $("#dt").on("click", "input:checkbox", function (e) {
                var stat = $(this).attr("checked");
                if (stat == "checked") {
                    $(this).parent().parent().removeClass("bg_uncheck").addClass("bg_check");
                } else {
                    $(this).parent().parent().removeClass("bg_check");
                }
            });



            /**计算金额和税额的 逻辑**/
            //表格内部计算函数
            function getJe() {
                var total = 0;
                var t = $("#dt").find("input[name='je'],input[name='je1']").each(function (i) {
                    var v = $(this).val();
                    if (!v) v = 0;
                    total += parseFloat(v);
                });
                return total.toFixed(2);
            }

            function getSe() {
                var total = 0;
                var t = $("#dt").find("input[name='se'],input[name='se1']").each(function (i) {
                    var v = $(this).val();
                    if (!v) v = 0;
                    total += parseFloat(v);
                });
                return total.toFixed(2);
            }

            function setSum() {
                var total = getJe();
                var mse = getSe();
                $("#sumje").val(total);
                $("#sumse").val(mse);
                var sumse = $("#sumse").val();
                if (!sumse) sumse = 0
                if (!window.hasTax) {
                    var sum = parseFloat(total) + parseFloat(sumse);
                } else {
                    var sum = parseFloat(total);
                }
                sum = parseFloat(sum).toFixed(2);
                $("#sum").val(sum);
                $("#sumhans").val(changeMoneyToChinese(sum));
            }



            //Todo 匹配税收编码
            // window.spbm = {};
            // $("#dt").on('blur', "input[name='spmc']", function (e) {
            //     var self = $(this);
            //     var orginName = self.val();
            //     if (orginName == '') {
            //         return ;
            //     }
            //     window.sIndex = layer.open({
            //         type: 2,
            //         id: 'myspbm',
            //         title: '商品编码表',
            //         fixed: true,
            //         scrollbar: true,
            //         area: ['750px', '580px']
            //         , content: '/manual/spbm'
            //         ,end:function(){
            //             var sFrm = $(self.next()[0]).val();
            //             if (!$.isEmptyObject(spbm)) {
            //                 $(self.next()[0]).val(spbm.HBBM);
            //
            //                 var ttt = orginName.replace(/^[\*].+\*/g , '');
            //                 self.val("*"+spbm.FLBMJC+"*"+ttt);
            //                 window.spbm = {};
            //             }
            //         }
            //     });
            // });

            //Todo:选择商品
            window.product = {};
            $("#dt").on('click' , ".triangle" , function(e){
                var self = $(this);

                window.sIndex = layer.open({
                    type: 2,
                    id: 'myproduct',
                    title: '商品表',
                    fixed: true,
                    scrollbar: true,
                    area: ['750px', '580px']
                    , content: '/manual/product'
                    ,end:function(){
                        if ($.isEmptyObject(product)) {
                            return ;
                        }
                        var ptr = self.parent().parent();
                        ptr.find("input[name='productid']").val('').val(product.id);
                        ptr.find("input[name='spmc']").val('').val(product.spmc);
                        ptr.find("input[name='spbm']").val('').val(product.spbm);
                        ptr.find("input[name='ggxh']").val('').val(product.ggxh);
                        ptr.find("input[name='jldw']").val('').val(product.jldw);
                        product = {};
                    }
                });
            });

            function calculator() {
                //横向计算
                function setTax(mSelf, type) {
                    var self = $(mSelf);
                    var ptr = self.parent().parent();
                    if (type == "je") {
                        var tje = self.val();
                        var tsl = ptr.find("input[name='sl']").val();
                    } else if (type == "sl") {
                        var tsl = self.val();
                        var tje = ptr.find("input[name='je']").val();
                    } else if (type == "slv") {
                        var tje = ptr.find("input[name='je']").val();
                        var tsl = ptr.find("input[name='sl']").val();
                    }

                    var tdj = ptr.find("input[name='dj']");
                    tje = parseFloat(tje);
                    tsl = parseFloat(tsl);
                    tslv = parseFloat(tslv);
                    if (!isNaN(tje) && !isNaN(tsl)) {
                        var tres = (parseFloat(tje) / parseFloat(tsl));
                        tdj.val(tres.toFixed(6));
                        if (type == "je") {
                            self.val(tje.toFixed(2));
                        }
                    }

                    var tse = ptr.find("input[name='se']");
                    var tslv = ptr.find("select[name='slv'] , input[name='slv']").val();
                    tslv = parseFloat(tslv);
                    var retSe = 0;
                    if (window.hasTax) retSe = (tje / (1 + tslv)) * tslv;
                    else retSe = tje * tslv;
                    if (!isNaN(retSe)) tse.val(retSe.toFixed(2));
                }

                $("input[name='je']").blur(function (e) {
                    setTax(this, "je");

                    //纵向计算
                    setSum();
                });
                $("#dt").on("blur", "input[name='je']", function (e) {
                    setTax(this, "je");

                    //纵向计算
                    setSum();
                });

                $("input[name='sl']").blur(function (e) {
                    setTax(this, "sl");

                });
                $("#dt").on("blur", "input[name='sl']", function (e) {
                    setTax(this, "slv");
                });

                $("input[name='se']").blur(function (e) {
                    setSum();
                });
                $("#dt").on("blur", "input[name='se']", function (e) {
                    setSum();
                });
                $("#dt").on("change", "select[name='slv']", function (e) {//Todo:修改
                    setTax(this, "slv");
                    setSum();
                });

                $("#dt").on("focus", "input[name='je1']", function (e) {//Todo:弹框
                    var currentRow = $(this).parent().parent();
                    var lastRow = $(this).parent().parent().prev()[0];
                    var win = $.ligerDialog.open({
                        title: '填写折扣', name: 'windiscount', width: 400, height: 280, url: '../../invoice/discount.aspx',
                        data: {
                            info: lastRow
                        },
                        buttons: [
                            {
                                text: '确定', onclick: function (item, dialog) {
                                    //var rowsdata = dialog.frame.liger.get("maingrid").getCheckedRows();
                                    var zk = dialog.frame.liger.get("form1").getData();
                                    var tslv = parseFloat(zk.slv);
                                    zk.se = ((parseFloat(zk.zk) / (1 + tslv)) * tslv).toFixed(3);
                                    //$("#dt").append(getDiscountRow(zk, ++count));
                                    win.close();
                                    currentRow.find("input[name='spmc']").val(zk.discount);
                                    currentRow.find("input[name='je1']").val(parseFloat(zk.zk) * -1);
                                    currentRow.find("input[name='se1']").val(parseFloat(zk.se) * -1);
                                    setSum();
                                    setTax();
                                }, cls: 'l-dialog-btn-highlight'
                            },
                            {
                                text: '取消', onclick: function () {
                                    win.close();
                                }
                            }
                        ]
                    });

                });
                setSum();
            }

            calculator();
            /**计算金额和税额的 逻辑**/


    }
})(jQuery ,window , document);